package com.kzj.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kzj.domain.vo.UserLoginVO;
import com.kzj.global.constant.GlobalConstant;
import com.kzj.global.properties.JwtProperties;
import com.kzj.global.threadLocal.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UserLoginHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(jwtProperties.getUserTokenName());
        log.info(token);
        if(token==null)
        {
            response.setCharacterEncoding(GlobalConstant.CHARSET_UTF_8);
            response.setStatus(401);
            response.getWriter().write(GlobalConstant.PLEASE_LOGIN);
            log.warn("非法请求,token为空");
            return false;
        }
        String s = stringRedisTemplate.opsForValue().get(token);
        if(s==null)
        {
            response.setCharacterEncoding(GlobalConstant.CHARSET_UTF_8);
            response.setStatus(404);
            response.getWriter().write(GlobalConstant.LOGIN_INFO_EXPIRE);
            log.warn("非法请求,token不存在");
            return false;
        }
        stringRedisTemplate.opsForValue().set(token,s,GlobalConstant.LOGIN_INFO_TTL, TimeUnit.MINUTES);
        JSONObject jsonObject = (JSONObject)JSONObject.parse(s);
        UserLoginVO user = jsonObject.toJavaObject(UserLoginVO.class);
        UserThreadLocal.setUser(user);
        return true;
    }
}
